<template>
  <el-dialog title="生产排产" v-model="props.visible" width="70%" :before-close="handleClose" align-center>
    <el-form :model="form" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单编号">
            <el-input v-model="form.workorderCode" readonly placeholder="请输入工单编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单名称">
            <el-input v-model="form.workorderName" readonly placeholder="请输入工单名称"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="来源类型">
            <el-radio-group v-model="form.orderSource" disabled>
              <el-radio label="ORDER">客户订单</el-radio>
              <el-radio label="STORE">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.orderSource === 'ORDER'">
          <el-form-item label="订单编号">
            <el-input v-model="form.clientOrderCode" readonly placeholder="请输入订单编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="排产状态">
            <el-select v-model="form.status" readonly placeholder="请选择排产状态">
              <el-option label="草稿" value="PREPARE"/>
              <el-option label="已确定" value="CONFIRMED"/>
              <el-option label="审批中" value="APPROVING"/>
              <el-option label="已审批" value="APPROVED"/>
              <el-option label="已完成" value="FINISHED"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="产品编号">
            <el-input v-model="form.productCode" readonly placeholder="请输入产品编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称">
            <el-input v-model="form.productName" readonly placeholder="请输入产品名称"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="form.productSpc" readonly placeholder="请输入规格型号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位">
            <el-input v-model="form.unitOfMeasure" readonly placeholder="请输入单位"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="工单数量">
            <el-input v-model="form.quantity" readonly placeholder="请输入工单数量"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求日期">
            <el-date-picker v-model="form.requestDate" readonly placeholder="选择日期" type="date"/>
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="form.orderSource === 'ORDER'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编号">
              <el-input v-model="form.clientCode" readonly placeholder="请输入客户编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input v-model="form.clientName" readonly placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-form-item label="备注">
        <el-input v-model="form.remark" readonly type="textarea" rows="2"/>
      </el-form-item>
    </el-form>

    <div>
      <el-steps style="max-width: 100%" :active="activeNum" finish-status="success" simple>
        <el-step
            v-for="(step,index) in stepData"
            :key="index"
            :description="step.processName"
            :title="step.processName"
            @click.native="on_click(index,step.processCode)"
        />
      </el-steps>

      <div class="tableBody">
        <div class="mb-4">
          <el-button type="primary" plain size="small" @click="handleAdd">
            <el-icon>
              <Plus/>
            </el-icon>
            新增
          </el-button>
          <el-button type="success" plain size="small" @click="handleEdit" :disabled="select_order_number!=1">
            <el-icon>
              <Edit/>
            </el-icon>
            修改
          </el-button>
          <el-button type="danger" plain size="small" @click="handleDelete" :disabled="select_order_number==0">
            <el-icon>
              <Delete/>
            </el-icon>
            删除
          </el-button>
        </div>
        <el-table :data="tableData" border ref="multipleTable" style="width: 100%;margin-top: 10px" height="120px"
                  :header-cell-style="{ 'font-size':'12px' }" max-height="120px"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="taskCode" label="任务编号" width="100px">
            <template #default="scope">
              <el-tooltip :content="scope.row.taskCode" raw-content placement="top-start" v-if="scope.row.taskCode">
              <span v-if="scope.row.taskCode && scope.row.taskCode.length <= 6">
                {{ scope.row.taskCode }}
              </span>
                <!-- 如果单元格中有值，并且值得长度大于15，便使用substr截取0-15的内容显示，后面的变成省略号-->
                <span v-if="scope.row.taskCode && scope.row.taskCode.length > 6">
                {{ scope.row.taskCode.substring(0, 6) + "..." }}
              </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="taskName" label="任务名称" width="100px">
            <template #default="scope">
              <el-tooltip :content="scope.row.taskName" raw-content placement="top-start" v-if="scope.row.taskName">
              <span v-if="scope.row.taskName && scope.row.taskName.length <= 5">
                {{ scope.row.taskName }}
              </span>
                <!-- 如果单元格中有值，并且值得长度大于15，便使用substr截取0-15的内容显示，后面的变成省略号-->
                <span v-if="scope.row.taskName && scope.row.taskName.length > 5">
                {{ scope.row.taskName.substring(0, 5) + "..." }}
              </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="workstationCode" label="工作站编号" width="100px"/>
          <el-table-column prop="workstationName" label="工作站名称" width="100px"/>
          <el-table-column prop="quantity" label="排产数量" width="100px"/>
          <el-table-column prop="quantityProduced" label="已生产数量" width="100px"/>
          <el-table-column prop="startTime" label="开始生产日期" width="150px"/>
          <el-table-column prop="duration" label="生产时长" width="100px"/>
          <el-table-column prop="endTime" label="预计完成日期" width="150px"/>
          <el-table-column prop="colorCode" label="显示颜色" width="100px">
            <template #default="scope">
              <el-color-picker v-model="scope.row.colorCode" show-alpha disabled/>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150px">
            <template #default="scope">
              <el-button type="primary" plain size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button type="danger" plain size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <add-task :add-visible="addVisible" :processCode="tableChange" :procedureCode="procedureCode" :form="form"
                @close="CloseDialog"/>
      <updata-task :add-visible="updataVisible" :processCode="tableChange" :form="form" :procedureCode="procedureCode"
                   :datas="multipleSelection" @close="CloseDialog"/>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, watch} from 'vue'
import {Delete, Edit, Plus} from '@element-plus/icons-vue'
import {deleteTask, findProcess, taskFindProcess} from "@/apis/zyj/ProductionSceduling.js";
import AddTask from "@/components/ProductionScheduling/AddTask.vue";
import UpdataTask from "@/components/ProductionScheduling/updataTask.vue"
import {ElMessage, ElMessageBox} from "element-plus";

const props = defineProps({
  visible: Boolean,
  dataTable: Array
})
const emit = defineEmits(['close'])

watch(() => props.visible, (newValue) => {
  Object.assign(form, {...props.dataTable})
  taskFindProcess(form.productCode).then(res => {
    if (res.length !== 0) {
      Object.assign(stepData, res)
      activeNum.value = res[0].orderNumber;
      tableChange.value = res[0].processCode
    } else {
      ElMessage.error("请为该产品绑定流程")
      stepData.length = 0
      activeNum.value = 0;
    }
  })
  tableInit(form.workorderCode, tableChange.value)
})

const procedureCode = ref()
const stepData = reactive([])

// 组成工序的多选
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理

const form = reactive({
  workorderCode: '',
  workorderName: '',
  orderSource: '',
  clientOrderCode: '',
  productCode: '',
  productName: '',
  productSpc: '',
  unitOfMeasure: '',
  quantity: '',
  requestDate: '',
  clientCode: '',
  clientName: '',
  remark: '',
  status: '',
})

const tableData = ref([])
const activeNum = ref(null);
const tableChange = ref()
const addVisible = ref(false)
const updataVisible = ref(false)

function tableInit(a, p) {
  findProcess(a, p).then(res => {
    tableData.value.length = 0
    tableData.value = res
  })
}

const on_click = (r, p) => {
  activeNum.value = r
  tableChange.value = p
  tableInit(form.workorderCode, p);
}

const CloseDialog = () => {
  addVisible.value = false
  updataVisible.value = false
  tableInit(form.workorderCode, tableChange.value)
}

const handleClose = () => {
  emit('close')
}

const handleAdd = () => {
  console.log("工序", stepData)
  procedureCode.value = stepData[0].procedureCode
  addVisible.value = true
}

const handleEdit = (row) => {
  updataVisible.value = true
  if (row.taskId != null) {
    multipleSelection.value = {...row}
  } else {
    multipleSelection.value = {...multipleSelection.value[0]}
  }
  console.log("行", multipleSelection.value)
}

const handleDelete = (row) => {
  if (row.taskId != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.taskId != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.taskId)
        }
        deleteTask(select_orderId.value).then((res) => {
          if (res == '成功') {
            tableInit(form.workorderCode, tableChange.value)
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = '0';
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

const handleSubmit = () => {
  handleClose()
}

const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.taskId);
      }
    });
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.justify-between {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tableBody {
  padding: 40px;
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}
</style>